package com.aaa.service.impl;

import com.aaa.service.UploadService;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class UploadServiceImpl implements UploadService {
    @Override
    public String uploadFile(MultipartFile file) {
        // 文件上传之后   数据库里面存放   上传的路径
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        // LTAI5t6H7BoF9S8tLFufWhEs
        //k6t2zkwYqNz9he62BiGslx60R79IGx
        String accessKeyId = "LTAI5t6H7BoF9S8tLFufWhEs";
        String accessKeySecret = "k6t2zkwYqNz9he62BiGslx60R79IGx";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "yuyonglitest";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = "";
        String oldname=file.getOriginalFilename();
        objectName = System.currentTimeMillis() + oldname.substring(oldname.lastIndexOf("."));
        System.out.println("objectName = " + objectName);
        //String objectName = "exampledir/exampleobject.txt";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file.getInputStream());
            // 上传字符串。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        }  catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        // 文件的路径
        String path = "https://"+bucketName+"."+endpoint+"/"+objectName;
        return path;
    }
}
